#include "fileUtils.h"
#include "coordRef.h"
#include <fstream>
#include <regex>
#include <algorithm>
#include <ctype.h>


#ifdef MSWINDOWS
#include <windows.h>
#include <dos.h>
#include <direct.h>
#include <fcntl.h>
#include <io.h>
#include <sys/types.h>
#include <sys/stat.h>
#else
#include <dirent.h>
#include <fcntl.h>
#include <sys/param.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#endif

#ifdef MSWINDOWS
  static const char* separator_set = "\\/";
  static const char preferred_separator = '\\';
#else
  static const char* separator_set = "/";
  static const char preferred_separator = '/';
#endif

static bool is_separator(char ch)
{
  for (int i = 0; separator_set[i]; i++)
  {
     if (separator_set[i] == ch)
      return true;
  }
  return false;
}

std::vector<std::string> FileUtils::SpliteStr(const std::string& in, const std::string& delim)
{
    std::regex re{delim};
    return std::vector<std::string>{
        std::sregex_token_iterator(in.begin(), in.end(), re, -1),
        std::sregex_token_iterator()};
}

std::string FileUtils::filename_part(const std::string &spec)
{
	std::size_t i = spec.size();
	while (i--)
	{
		if (spec[i] == '/')
			return spec.substr(i + 1, spec.size() - i - 1);
	}
	return spec;
}

std::string FileUtils::base_name_part(const std::string &filepath)
{
	std::string fname = filename_part(filepath);
	std::string::size_type i = fname.find_last_of('.');
	if (i != 0 && i != std::string::npos)
		fname.erase(i, fname.size() - i);
	return fname;
}

std::string FileUtils::file_concate(const std::string& directory, const std::string& filename)
{
    std::string result = directory;
    // if directory is empty then no directory part will be added
    // add trailing slash if the directory was specified and does not have a trailing slash
    if (!result.empty() && !is_separator(result[result.size()-1]))
      result += preferred_separator;
    // if filename is null or empty, nothing will be added so the path is then a directory path
    result += filename;
    return result;
}

 bool FileUtils::folder_create(const std::string& directory)
 {
#ifdef MSWINDOWS
   return mkdir(directory.c_str()) == 0;
#else
   return mkdir(directory.c_str(), 0777) == 0;
#endif
 }